<div class="row">
    <div class="col-xs-12">
        <div class="box">
            <div class="box-header">
                <h3 class="box-title">订单查询</h3>

                <div class="box-tools">

                    <div class="input-group input-group-sm" style="width: 350px;">
                        <input type="text" name="table_search" id="searchNameId"
                               class="form-control pull-right" placeholder="订单名称">
                        <div class="input-group-btn">
                            <button type="button" class="btn btn-default btn-search">
                                <i class="fa fa-search"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <!-- /.box-header -->
            <div class="box-body table-responsive no-padding">
                <table class="table table-hover">
                    <thead>
                    <tr>
                        <th>选择</th>
                        <th>订单号</th>
                        <th>订单名称</th>
                        <th>用户姓名</th>
                        <th>实际总价</th>
                        <th>发货地址</th>
                        <th>创建时间</th>
                        <th>修改时间</th>
                        <th>付款状态</th>
                        <th>发货状态</th>
                        <th>订单明细</th>
                        <th>点击发货</th>
                    </tr>
                    </thead>
                    <tbody id="tbodyId"></tbody>
                </table>
            </div>
            <div id="pageId" class="box-footer clearfix">
            </div>
            <!-- /.box-body -->
        </div>
        <!-- /.box -->
    </div>
</div>
<script type="text/javascript">

    //分页浏览功能
    $(document).ready(function () {
        $("#pageId").load("/modules/common/page.html", doGetObjects); //执行方法查询数据加载页面
        $(".input-group-btn")
            .on("click", ".btn-search", doQueryObjects)    //搜索方法
        $("tbody").on("click", ".btn-order-sub", doTypeById);		//跳转详情页按钮方法
        $("tbody").on("click", ".btn-delivery", doDeliveryId);
        $("tbody").on("click", ".btn-option-address", showAddress);
    });

    //跳转到商品配置页
    function doTypeById() {
        //基于id进行查询并加载编辑页面
        let typeUrl = "/modules/sys/order_sub_list.html"
        let id = $(this).parents("tr").data("rowData").id;
        $("#mainContentId").data("orId", id); //加载数据到页面
        $("#mainContentId").load(typeUrl) //赋予url到修改用户
    }

    function updateAddress(id,addressId,sendStatus) {
        console.log(id);
        console.log(addressId);
        if(addressId=="选择"){
            return;
        }
        let url =`${baseUrl}/shoppingback/ddOrderInfo/updateAddress/${id}/${addressId}`;
        $.ajax({
            url:url,crossDomain: true, xhrFields: {withCredentials: true},method:"put",async: false,
            headers : {"Authorization": "Bearer " + window.localStorage.getItem("accessToken")},
            success(result){
                if(result.status==401){
                    alert(result.msg);
                    return;
                }
                if(result.status==403){
                    alert(result.msg);
                    return;
                }
            }
        });
        doGetObjects();
    }

    function showAddress(){
        let id = $(this).parents("tr").data("rowData").id;
        let userId = $(this).parents("tr").data("rowData").userId;
        let url = `${baseUrl}/selectAddress/${userId}`;
        let address ;
        $.ajax({
            url, crossDomain: true, xhrFields: {withCredentials: true},async: false,
            headers : {"Authorization": "Bearer " + window.localStorage.getItem("accessToken")},
            success(result) {
                if(result.status==401){
                    alert(result.msg);
                    return;
                }
                if(result.status==403){
                    alert(result.msg);
                    return;
                }
                if (result.success) {
                    address=result.data;
                } else {
                    alert(result.msg);
                }
            }
        });
        if ($(this).data("check")==undefined) {
            let option = `<option class="btn option" name="addressId" value='[id]'>[name]</option>` //载入类型选择
            address.forEach(item => {
                //记住每次replace时都会产生一个新的字符串对象
                var newInput =
                    option.replace("[id]", item.id)
                        .replace("[name]", item.address);
                $(this).append(newInput)    //插入类型选择
            });
            $(this).data("check",false);
        }
        addressId = $(this).val()
        updateAddress(id,addressId);
    }

    function doDeliveryId(){
        let data = $(this).parents("tr").data("rowData");
        console.log(data);
        if(data.payStatus==0){
            alert("该订单未付款!");return;
        }
        if(data.sendStatus==1){
            alert("该订单已经发货!");return;
        }
        let id = data.id;
        let url = `${baseUrl}/shoppingback/ddOrderInfo/${id}/1`;
        $.ajax({url:url,method:"put",crossDomain: true, xhrFields: {withCredentials: true},
            headers: {"Authorization": "Bearer " + window.localStorage.getItem("accessToken")},
            success(result) {
                if(result.status==401){
                    alert(result.msg);
                    return;
                }
                if(result.status==403){
                    alert(result.msg);
                    return;
                }
                alert(result.msg);
                doGetObjects();
            },
            error(){
                alert("服务器忙,请稍后再试");
            }
        });
    }

    //点击id选择用户
    function doGetCheckedId() {
        return $("tbody input[name='radioId']:checked").val();
    }

    //保存页数并显示
    function doLoadPage(title) {
        $("#mainContentId").load(url, function () {
            $(".box-title").html(title);
        })
    }

    //处理查询按钮事件
    function doQueryObjects() {
        $("#pageId").data("pageNum", 1);
        doGetObjects();
    }

    //页面加载完成异步加载当前页数据
    function doGetObjects() {
        let url = `${baseUrl}/shoppingback/ddOrderInfo`;
        let pageNum = $("#pageId").data("pageNum");
        if (!pageNum) pageNum = 1;
        let params = {"pageNum": pageNum}
        params.query = $("#searchNameId").val().trim();
        $.ajax({
            url: url, data: params, crossDomain: true, xhrFields: {withCredentials: true},
            headers: {"Authorization": "Bearer " + window.localStorage.getItem("accessToken")},
            success(result) {
                if(result.status==401){
                    alert(result.msg);
                    return;
                }
                if(result.status==403){
                    alert(result.msg);
                    return;
                }
                doHandleQueryResponseResult(result);
            }
        });
    }

    //处理搜索框结果
    function doHandleQueryResponseResult(result) {
        if (result.success) {
            doSetTableBodyRows(result.data.rows);
            doSetPagination(result.data);
        } else {
            alert(result.msg);
        }
    }

    //通过服务端返回的数据初始化页面
    function doSetTableBodyRows(data) {
        //1.获取tbody对象，并清空内容
        let tBody = $("#tbodyId");
        tBody.empty();
        //2.迭代data内容将数据追加到tbody中
        data.forEach(item => {
            let tr = $("<tr></tr>");
            tr.data("rowData", item);
            let tds = doCreateTds(item);
            tr.append(tds);
            tBody.append(tr);
        });
    }

    function doCreateTds(row) {
        return `<td><input type='radio' name='radioId' value='${row.id}' ></td>
         <td>${row.id}</td>
         <td>${row.orderName}</td>
	     <td>${row.ddUsersInfo.username}</td>
	     <td>${row.totalPrice}</td>
	     <td>${row.addressInfo.address}<select class="btn-option-address"><option>选择</option></select></td>
	     <td>${getFormatDate2(row.createTime)}</td>
	     <td>${getFormatDate2(row.updateTime)}</td>
	     <td>${row.payStatus==1?"已付款":"未付款"}</td>
	     <td>${row.sendStatus==1?"已发货":"未发货"}</td>
	     <td><button type='button' class='btn btn-primary btn-order-sub'>订单详情</button></td>
         <td><button type='button' class='btn btn-default btn-delivery'>发货</button></td>`;
    }

    function getFormatDate2(time) {
        var nowDate = new Date(time);
        var year = nowDate.getFullYear();
        var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
        var date = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
        var hour = nowDate.getHours() < 10 ? "0" + nowDate.getHours() : nowDate.getHours();
        var minute = nowDate.getMinutes() < 10 ? "0" + nowDate.getMinutes() : nowDate.getMinutes();
        var second = nowDate.getSeconds() < 10 ? "0" + nowDate.getSeconds() : nowDate.getSeconds();
        return year + "年" + month + "月" + date + "日" + hour + ":" + minute + ":" + second;
    }
</script>




